package com.coldlz.mmp.proxy.handlerserver;

import com.coldlz.mmp.proxy.UserContext;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 仅做一次Established响应，仅用于处理HTTPS的首次连接
 */
public class ServerEstablishedHandler extends ChannelDuplexHandler {
    private static final Logger log = LoggerFactory.getLogger(ServerEstablishedHandler.class);

    private final UserContext userContext;

    public ServerEstablishedHandler(UserContext userContext) {
        this.userContext = userContext;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        byte[] establishedContent = "HTTP/1.1 200 Connection Established\r\n\r\n".getBytes();
        ctx.writeAndFlush(Unpooled.wrappedBuffer(establishedContent)).addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess() && future.cause() != null) {
                log.error("响应 established fail..", future.cause());
            }else {
                log.info("响应 established Successful..");
            }
        });
        if (!ctx.isRemoved()) {
            ctx.pipeline().remove(this);
        }
        ctx.fireChannelRead(obj);
    }
}
